package com.mycloud.dictionary.dao;

import com.mycloud.core.dao.HibernateGenericDao;
import com.mycloud.dictionary.model.WordTranslation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.jpa.JpaCallback;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceException;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: dell
 * Date: 12/14/11
 * Time: 5:27 PM
 * To change this template use File | Settings | File Templates.
 */
@Repository
public class HibernateDictionaryDao extends HibernateGenericDao implements DictionaryDao{
    public void persist(String word, String translation) {
        WordTranslation wordTranslation = new WordTranslation();
        wordTranslation.setWord(word);
        wordTranslation.setTranslation(translation);
        persist(wordTranslation);
    }

    public List<String> getAll() {
        return getJpaTemplate().find("select word from WordTranslation");
    }

    public List<String> getAllWordsWordsNotHavingAudioPath() {
        return getJpaTemplate().find("select word from WordTranslation where audioPath is null");
    }

    public String getDatabaseTranslation(final String word) {
        return getJpaTemplate().execute(new JpaCallback<String>() {
            public String doInJpa(EntityManager entityManager) throws PersistenceException {
                List<String> list = (List<String>)entityManager.createQuery("select translation from WordTranslation where word = :word")
                        .setParameter("word", word).getResultList();
                return list != null && list.size() > 0 ? list.get(0) : "";
            }
        }) ;
    }

    public void setAudioPath(final String word, final String audioPath) {
        getJpaTemplate().execute(new JpaCallback<Object>() {
            public Object doInJpa(EntityManager entityManager) throws PersistenceException {
                return entityManager.createQuery("update WordTranslation set audioPath = :audioPath where word = :word")
                        .setParameter("audioPath", audioPath).setParameter("word", word).executeUpdate();
            }
        });
    }

    @Autowired
    public HibernateDictionaryDao(EntityManagerFactory mycloudDataSource) {
        setEntityManagerFactory(mycloudDataSource);
    }


}
